﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Code.BLL;
using Code.Models;
using QianBuo.Lottery.Web.Commen;
using QianBuo.Lottery.Web.Models;
using Code.Commen;
using QianBuo.Lottery.Web.Models.User;
using System.Security.Cryptography;

namespace QianBuo.Lottery.Web.Controllers
{
    public class UserController : BaseController
    {
        //
        // GET: /User/
        #region 用户详情
        public ActionResult Detail(string msg)
        {
            if (!string.IsNullOrEmpty(msg))
                ViewData["msg"] = msg.AlertOffPage();
                Guid uid = LoginUserID;
                UserManage um = new UserManage();
                var user = um.Select(s => s.FirstOrDefault(p=>p.ID==uid));
                var person = user.Person;
                UserOptionManage uom = new UserOptionManage();
                var userOption = uom[uid, Option_User_Key.Lock_info];
                var userDetail = new UserDetail()
                {
                    LoginName = user.LoginName,
                    QQ = person.QQ,
                    Tel = person.Phone,
                    BankCardNo = person.BankCardNo,
                    Name = person.Name ?? "",
                    BankID = person.BankID,
                    PayAccount = person.PayAccount,
                    Email = ReplaceEmail(person.Email),
                    BankCityID = person.BankCityID,
                    BankCityName = person.BankCityID.HasValue ? person.BankCity.CityName : "",
                    BankCityProvinceName = person.BankCityID.HasValue ? person.BankCity.Province.ProvinceName : "",
                    BankStreetName = person.BankStreet ?? "",
                    BankName = person.BankID.HasValue ? person.Bank.Name : "",
                    Locked = userOption == null ? false : userOption.ToBool(false),
                    IsSave = !string.IsNullOrEmpty(person.Email)
                };
                return View(userDetail);
        }

        [HttpPost]
        [MultiButton(Name = "save")]
        public ActionResult Detail(UserDetail detail)
        {
            
            if (ModelState.IsValid)
            {
                if (!detail.CheckCode.Equals(TempData["EditInfo"] as string, StringComparison.CurrentCultureIgnoreCase))
                {
                    ModelState.AddModelError("CheckCode", "验证码不正确");
                    return View(detail);
                }

                Guid uid = LoginUserID;
                var userOption = new UserOptionManage();
                var lock_Info = userOption[uid, Option_User_Key.Lock_info];
                var locked = lock_Info == null ? false : lock_Info.ToBool(false);
                if (locked)
                {
                    ViewData["msg"] =  "".Redirect("当前状态已锁定，您不能修改。");
                    return View(detail);
                }
                else
                {
                    UserManage um = new UserManage();
                    CommenManage<Person> cm_p=new CommenManage<Person>();
                    var user = cm_p.Select(s => s.Where(p => p.UserID == uid).Select(p => new {p.Email,p.BankID,p.BankCardNo,p.BankCityID,p.BankStreet,p.QQ,p.Phone,p.Name,p.PayAccount}).FirstOrDefault());
                    var flag = false;
                    if (string.IsNullOrEmpty(user.Email)&&!string.IsNullOrEmpty(detail.Email))
                        flag = um.BoolEmail(detail.Email);
                    if (flag)
                    {
                        ModelState.AddModelError("Email", "该邮箱已有人使用，请重新输入！");
                    }
                    else
                    {
                        if(string.IsNullOrEmpty(user.BankCardNo)&&!string.IsNullOrEmpty(detail.BankCardNo))
                            flag = um.Select(s => s.Select(p => p.Person.BankCardNo).Contains(detail.BankCardNo));
                        if (!string.IsNullOrEmpty(detail.BankCardNo) && flag)
                            ModelState.AddModelError("BankCardNo", "该银行卡号已有人使用，请重新输入。");
                        else
                        {
                            flag = um.BoolLoginPwd(uid, detail.LoginPwd);
                            if (flag)
                            {
                                var updatePerson = new NameValue<string, object>();
                                if (string.IsNullOrEmpty(user.Email))
                                    updatePerson.Add(new NameValueItem<string, object>("Email", detail.Email));
                                if (string.IsNullOrEmpty(user.BankCardNo)||detail.OldDetail.BankCardNo!=detail.BankCardNo)
                                    updatePerson.Add(new NameValueItem<string, object>("BankCardNo", detail.BankCardNo));
                                if (!user.BankID.HasValue||detail.BankID!=detail.OldDetail.BankID)
                                    updatePerson.Add(new NameValueItem<string, object>("BankID", detail.BankID));
                                if (!user.BankCityID.HasValue||detail.BankCityID!=detail.OldDetail.BankCityID)
                                    updatePerson.Add(new NameValueItem<string, object>("BankCityID", detail.BankCityID));
                                if (string.IsNullOrEmpty(user.PayAccount) || detail.PayAccount != detail.OldDetail.PayAccount)
                                    updatePerson.Add(new NameValueItem<string, object>("PayAccount", detail.PayAccount));
                                if (string.IsNullOrEmpty(user.BankStreet)||detail.BankStreetName!=detail.OldDetail.BankStreetName)
                                    updatePerson.Add(new NameValueItem<string, object>("BankStreet", detail.BankStreetName));
                                if(string.IsNullOrEmpty(user.Name)||detail.Name!=detail.OldDetail.Name)
                                    updatePerson.Add(new NameValueItem<string, object>("Name", detail.Name));
                                if(detail.QQ!=detail.OldDetail.QQ)
                                    updatePerson.Add(new NameValueItem<string, object>("QQ", detail.QQ));
                                if(detail.OldDetail.Tel!=detail.Tel)
                                    updatePerson.Add(new NameValueItem<string, object>("Phone", detail.Tel));
                                if (updatePerson.Count > 0)
                                {
                                    var where = new NameValue<string, object>
                                    {
                                        {"UserID",uid}
                                    };
                                    int count = 0;
                                    string msg = "";
                                    if (updatePerson.Count > 0)
                                        count = um.UpdatePerson(updatePerson, where);
                                    if (count > 0)
                                    {
                                        msg += "".Redirect("修改成功！");
                                        detail.IsSave = true;
                                    }
                                    else
                                    {
                                        detail.Locked = false;
                                        msg = "".Redirect("操作失败，请稍后再试！");
                                    }
                                    ViewData["msg"] = msg;
                                }
                                else
                                {
                                    if(!string.IsNullOrEmpty(user.Email))
                                        detail.IsSave = true;
                                }
                            }
                            else
                            {
                                ModelState.AddModelError("LoginPwd", "密码不正确");
                            }
                        }
                    }
                }
            }
            return View(detail);
        }
        [HttpPost]
        [ActionName("Detail")]
        [MultiButton(Name = "save2")]
        public ActionResult Detail_Save([Bind(Exclude="Email")]UserDetail detail)
        {
            if(ModelState.Keys.Contains("Email"))
                ModelState["Email"].Errors.Clear();
            detail.Email = LoginUser.Email;
            return Detail(detail);
        }

        [HttpPost]
        [ActionName("Detail")]
        [MultiButton(Name = "lock")]
        public ActionResult Detail1(UserDetail detail)
        {
            if (string.IsNullOrEmpty(LoginUser.Email))
            {
                ViewData["msg"] = "您还没有设置邮箱，不能锁定.".AlertOffPage();
                return View(detail);
            }
            string msg=string.Empty;
            UserOptionManage uom = new UserOptionManage();
            var count = uom.Update(base.LoginUserID, Option_User_Key.Lock_info, "true");
            if (count > 0)
            {
                msg = "".Redirect("已成功锁定，您不能再做修改！");
                ViewData["msg"] = msg;

            }
            else
            {
                msg = "操作失败，请稍后再试！".AlertOffPage();
                ViewData["msg"] = msg;
            }
            detail.Email = LoginUser.Email;
            return View(detail);
        }
        public JsonResult GetDetailFreeKey()
        {
            var msg="";
            var flag = 0;
            var person = new UserManage().Select<Person,Person>(s => s.FirstOrDefault(p => p.UserID == LoginUserID));
            if (person == null || string.IsNullOrEmpty(person.Email))
                msg = "请选设置您的安全邮箱";
            else
            {
                var key = MD5.Create().ComputeHash(Guid.NewGuid().ToString());
                try
                {
                    new Jmail().Send(person.Email, "用户详情密钥", "解除用户详情锁定的临时密钥为:<br/>" + key, true);
                }
                catch { }
                TempData["DetailFreeKey"] = key;
                msg = "密钥已成功发送到您的安全邮箱";
                flag = 1;
            }
            return Json(new { msg,flag}, JsonRequestBehavior.AllowGet);
        }

        public JsonResult Detail_Free(string detailFreeKey)
        {
            var msg = "";
            var count = -1;
            var key = TempData["DetailFreeKey"] as string;
            if (string.IsNullOrEmpty(key))
                msg = "请先获取密钥";
            else if (key.Equals(detailFreeKey))
            {
                count = new UserOptionManage().Delete(new NameValue<string, object> {{"Key",Option_User_Key.Lock_info.ToString()},{"UserID",LoginUserID} });
                if (count > 0)
                    msg = "已成功解除锁定";
                else
                    msg = "操作失败！请重新操作.";
            }
            return Json(new {msg,count }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 申请提款
        public ActionResult TakeMoney()
        {
            try
            {
                string tms = CacheManage.OptionSite[Option_Site_Key.Site_Service_TakeMoneyStartTime].Value;
                string tme = CacheManage.OptionSite[Option_Site_Key.Site_Service_TakeMoneyEndTime].Value;
                DateTime dt1 = Convert.ToDateTime(tms);
                DateTime dt2 = Convert.ToDateTime(tme);
                DateTime dts = DateTime.Today.Add(new TimeSpan(dt1.Hour, dt1.Minute, dt1.Second));
                DateTime dte = DateTime.Today.Add(new TimeSpan(dt2.Hour, dt2.Minute, dt2.Second));
                DateTime dt3 = DateTime.Now;
                if (dts >= dte)
                {
                    if (dt3 < dte)
                        dt3 = dt3.AddDays(1);
                    dte = dte.AddDays(1);

                }
                if (!(dts < dt3 && dt3 < dte))
                {
                    string msg = string.Format("提款时间为{0}-{1}、请在提款受理时间内申请提款，谢谢合作！", dts.ToShortTimeString(), dte.ToShortTimeString());
                    ViewData["msg"] = msg.AlertOffPage(); 
                    ModelState.AddModelError("Error", msg);
                }
            }catch{ }

            Guid uid = LoginUserID;

            var model = new TakeMoney_Mod();
            model.Types = (Enum.GetValues(typeof(BankType)) as BankType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString() }).ToList();
            model.Types.Insert(0, new SelectListItem { Text = "选择类型", Value = "" });


            model.Balance = base.OnLineUsers[uid].Balance;
            //今天已提款次数
            TakeMoneyManage tmm = new TakeMoneyManage();
            var takeMoneyCount = tmm.TackMoneyCount_Today(uid);
            model.TakeMoneyCount = takeMoneyCount;
            TempData["TakeMoneyCount"] = model.TakeMoneyCount;

            var som = CacheManage.OptionSite;
            //最大提款次数
            var userOption = som[Option_Site_Key.User_MaxTakeMoneyCount];
            model.MaxTakeMoneyCount = userOption.ToInt32(50);
            //最小提款金额
            userOption = som[Option_Site_Key.User_MinTakeMoney];
            model.MinTakeMoney = userOption.ToDouble(0);
            return View(model);
        }

        [HttpPost]
        public ActionResult TakeMoney(TakeMoney_Mod model)
        {
            try
            {
                string tms = CacheManage.OptionSite[Option_Site_Key.Site_Service_TakeMoneyStartTime].Value;
                string tme = CacheManage.OptionSite[Option_Site_Key.Site_Service_TakeMoneyEndTime].Value;
                DateTime dt1 = Convert.ToDateTime(tms);
                DateTime dt2 = Convert.ToDateTime(tme);
                DateTime dts = DateTime.Today.Add(new TimeSpan(dt1.Hour, dt1.Minute, dt1.Second));
                DateTime dte = DateTime.Today.Add(new TimeSpan(dt2.Hour, dt2.Minute, dt2.Second));
                DateTime dt3 = DateTime.Now;
                if (dts >= dte)
                {
                    if (dt3 < dte)
                        dt3 = dt3.AddDays(1);
                    dte = dte.AddDays(1);

                }
                if (!(dts < dt3 && dt3 < dte))
                {
                    string msg = string.Format("提款时间为{0}-{1}、请在提款受理时间内申请提款，谢谢合作！", dts.ToShortTimeString(), dte.ToShortTimeString());
                    ViewData["msg"] = msg.AlertOffPage(); ;
                    ModelState.AddModelError("Error", msg);
                }
            }
            catch { }

            model.Types = (Enum.GetValues(typeof(BankType)) as BankType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString(), Selected = model.Type == p }).ToList();
            model.Types.Insert(0, new SelectListItem { Text = "选择类型", Value = "" });

            var som = CacheManage.OptionSite;
            //最大提款次数
            var userOption = som[Option_Site_Key.User_MaxTakeMoneyCount];
            model.MaxTakeMoneyCount = userOption.ToInt32(50);
            //最小提款金额
            userOption = som[Option_Site_Key.User_MinTakeMoney];
            model.MinTakeMoney = userOption.ToDouble(0);

            model.TakeMoneyCount = (int)TempData["TakeMoneyCount"];
            TempData["TakeMoneyCount"] = model.TakeMoneyCount;

            var user = new UserManage().Select(s => s.Where(p => p.ID == LoginUserID).Select(p => new { p.Account.Balance, p.TakeMoney,p.State,p.Person.BankCardNo,p.Person.PayAccount }).FirstOrDefault());
            model.Balance = (double)user.Balance;
            if (model.Type == BankType.Bank && string.IsNullOrEmpty(user.BankCardNo))
            {
                ViewData["msg"] = "您还没有设置银行卡信息，请先完善您的个人资料。".AlertOffPage();
                return View(model);
            }
            else if (model.Type == BankType.InlinePay && string.IsNullOrEmpty(user.PayAccount))
            {
                ViewData["msg"] = "您还没有设置网上支付账号，请先完善您的个人资料。".AlertOffPage();
                return View(model);
            }
            
            if (user.State != (short)UserState.Normal)
            {
                var state = (UserState)LoginUser.State;
                ViewData["msg"] = (state == UserState.Freez ? "您的金额已冻结，请先解冻!" : string.Format("您已被{0}，请与{1}联系！",state.GetName(),state==UserState.Locked_Manage?"上级代理":"管理员")).AlertOffPage();
                return View(model);
            }
            if (ModelState.IsValid)
            {
                var msg = "";
                if (model.Money == null)
                    msg = "请输入提款金额!";
                else if (model.Balance < model.Money)
                    msg = "您的余额不足本次提款，请重新输入。";
                else if (model.TakeMoneyCount >= model.MaxTakeMoneyCount)
                {
                    msg = "您今天已提款" + model.TakeMoneyCount + "次，您不能再提款了。";
                }
                else if (model.Money < model.MinTakeMoney)
                {
                    msg = "提款金额不能低于最少提款金额，请重新输入!";
                }
                else
                {
                    Guid uid = LoginUserID;
                    UserManage um = new UserManage();
                    var flag = um.BoolTakePwd(uid, model.TakePwd);
                    if (flag)
                    {
                        TakeMoneyManage tmm = new TakeMoneyManage();

                        var count = tmm.AddTackMoneyDetail(uid, model.Money.Value,model.Type.Value, "&" + (model.Msg ?? "").Replace("&", " "));
                        if (count > 0)
                        {
                            CacheManage.NewTakeMoneyUnDisposeCount++;
                            CacheManage.TakeMoneyUnDisposeCount++;
                            msg = "已成功申请提款！";
                            TempData["TakeMoneyCount"] = model.TakeMoneyCount + 1;
                            model.Balance = model.Balance - model.Money.Value;
                            base.LoginUser.Balance = model.Balance;
                            base.LoginUser.FreezeMoney += model.Money.Value;
                        }
                    }
                    else
                        msg = "您输入的提款密码不正确，请重新输入。";
                }
                ViewData["msg"] = "".Redirect( msg);
            }
            model.Money = null;
            model.TakePwd = null;
            model.Msg = null;
            return View(model);
        }
        #endregion

        #region 提款申请明细
        public ActionResult TakeMoneyDetail(int? page,TakeMoneys takeMoneys)
        {
            if (!page.HasValue)
                page = 1;
            TakeMoneys mondel;
            if (takeMoneys == null)
                mondel = new TakeMoneys();
            else
                mondel = takeMoneys;
            var states = Enum.GetValues(typeof(TakeMoneyState)).Cast<TakeMoneyState>().Select(p => new SelectListItem { Text = p.GetName(), Value = ((short)p).ToString() }).ToList();
            states.Add(new SelectListItem { Text="状态", Value=string.Empty });
            mondel.States = states;
            var where = " 1==1 ";
            var paramList = new List<object>();
            GetWhere(mondel.where, out where, out paramList);
            TakeMoneyManage tmm = new TakeMoneyManage();
            var list = tmm.GetTackMoneyList(LoginUserID,where,paramList.ToArray());

            mondel.PageInfo.CurrPage = page ?? 1;
            mondel.PageInfo.SunCount = list.Count();
            mondel.TakeMoneyList = list.OrderByDescending(p => p.AddTime).Skip((mondel.PageInfo.CurrPage - 1) * mondel.PageInfo.PageCount).Take(mondel.PageInfo.PageCount).ToArray();

            return View(mondel);
        }
        private void GetWhere(TakeMoneys.TackMoeny_Where where,out string str,out List<object> paramList)
        {
            str = " 1==1 ";
            paramList = new List<object>();
            if(where==null)
                return;
            if (where.ID.HasValue)
            {
                str += " and ID=@" + paramList.Count;
                paramList.Add(where.ID.Value);
                return;
            }
            if (where.AddTime_Start.HasValue)
            {
                str += " and AddTime >= @"+paramList.Count;
                paramList.Add(where.AddTime_Start.Value);
            }
            if (where.AddTime_End.HasValue)
            {
                str += " and AddTime < @" + paramList.Count;
                paramList.Add(where.AddTime_End.Value.AddDays(1));
            }
            if (where.DoTime_Start.HasValue)
            {
                str += " and DoTime >= @" + paramList.Count ;
                paramList.Add(where.DoTime_Start.Value);
            }
            if (where.DoTime_End.HasValue)
            {
                str += " and DoTime < @" + paramList.Count ;
                paramList.Add(where.DoTime_End.Value.AddDays(1));
            }
            if (where.Money.HasValue)
            {
                str += " and Money=@" + paramList.Count;
                paramList.Add((decimal)where.Money.Value);
            }
            if (where.State.HasValue)
            {
                str += " and State=@" + paramList.Count;
                paramList.Add(where.State.Value);
            }
        }
        [HttpPost]
        public ActionResult TakeMoneyDetail([Bind(Exclude = "PageInfo")]TakeMoneys model)
        {
            if (ModelState.IsValid)
            {
                return TakeMoneyDetail(1, model);
            }
            return TakeMoneyDetail(1, null);
        }
        #endregion

        #region 修改登录密码
        public ActionResult EditLoginPwd()
        {
            var user = new EditPwd();
            var um = new UserManage();
            var email = um.Select<Person, string>(s => s.Where(p => p.UserID == LoginUserID).Select(p => p.Email).FirstOrDefault());
            if (string.IsNullOrEmpty(email))
            {
                return RedirectToAction("Detail", new {msg="您还没有设置安全邮箱，请先设置邮箱！" });
            }
            user.Email = ReplaceEmail(LoginUser.Email);
            return View(user);
        }

        [HttpPost]
        [ActionName("EditLoginPwd")]
        [MultiButton(Name = "send")]
        public ActionResult EditLoginPwd_Send()
        {
            string email = LoginUser.Email;
            var pwdKey = MD5.Create().ComputeHash(Guid.NewGuid().ToString());
            TempData["pwdKey"] = pwdKey;
            try
            {
                new Jmail().Send(email, "修改登录密码", string.Format("您修改登录密码的密钥是:<br/>{0}", pwdKey), true);
                ViewData["msg"] = "密钥已发送到您的邮箱".AlertOffPage();
            }
            catch (AppException e)
            { 
                ViewData["msg"] = e.Message.AlertOffPage();
            }
            catch (Exception)
            { 
                ViewData["msg"] = "发送邮件失败，请稍后再操作！".AlertOffPage();
            }
            return View(new EditPwd { Email = ReplaceEmail(LoginUser.Email) });
        }
        [HttpPost]
        [MultiButton(Name = "edit")]
        public ActionResult EditLoginPwd(EditPwd model)
        {
            var newModel = new EditPwd { Email = ReplaceEmail(LoginUser.Email) };
            if (ModelState.IsValid)
            {
                var pwdKey = TempData["pwdKey"];
                if (pwdKey == null)
                {
                    ViewData["msg"] = "请先获取密钥！".AlertOffPage();
                    return View(newModel);
                }
                if (pwdKey.ToString() == model.InputPwdKey)
                {
                    var count = new UserManage().EditLoginPwd(LoginUserID, model.NewPwd);
                    if (count > 0)
                        ViewData["msg"] = "".Redirect( "登录密码修改成功！");
                    else
                    {
                        ViewData["msg"] = "操作失败！请稍后重新操作。".AlertOffPage();
                        TempData["pwdKey"] = pwdKey;
                    }
                }
                else
                {
                    ModelState.AddModelError("InputPwdKey", "密钥输入错误,请重新输入。");
                    TempData["pwdKey"] = pwdKey;

                }
            }
            return View(newModel);
        }
        #endregion

        #region 修改提款密码
        public ActionResult EditTakePwd()
        {
            var user = new EditPwd();
            var um = new UserManage();
            if (string.IsNullOrEmpty(LoginUser.Email))
            {
                return RedirectToAction("Detail", new { msg = "您还没有设置安全邮箱，请先设置邮箱！" });
            }
            user.Email = ReplaceEmail(LoginUser.Email);
            return View(user);
        }

        private string ReplaceEmail(string email)
        {
            if (string.IsNullOrEmpty(email))
                return string.Empty;
            var str = new System.Text.StringBuilder(email.Length);
            int i = email.IndexOf('@');
            email.Each((p, j) => { if (j > 0 && j < i - 1) str.Append('*'); else str.Append(p); });
            return str.ToString();
        }

        [HttpPost]
        [ActionName("EditTakePwd")]
        [MultiButton(Name = "send")]
        public ActionResult EditTakePwd_Send()
        {
            var email = LoginUser.Email;
            var pwdKey = MD5.Create().ComputeHash(Guid.NewGuid().ToString());
            TempData["pwdKey"] = pwdKey;
            try
            {
                new Jmail().Send(email, "修改提款密码", string.Format("您修改提款密码的密钥是:<br/>{0}", pwdKey), true);
                ViewData["msg"] = "密钥已发送到您的邮箱".AlertOffPage();
            }
            catch (AppException e)
            {
                ViewData["msg"] = e.Message.AlertOffPage();
            }
            catch (Exception)
            {
                ViewData["msg"] = "发送邮件失败，请稍后现操作！".AlertOffPage();
            }
            return View(new EditPwd { Email = ReplaceEmail(LoginUser.Email) });
        }
        [HttpPost]
        [MultiButton(Name = "edit")]
        public ActionResult EditTakePwd(EditPwd model)
        {
            var newModel = new EditPwd { Email = ReplaceEmail(LoginUser.Email) };
            if (ModelState.IsValid)
            {
                var pwdKey = TempData["pwdKey"];
                if (pwdKey == null)
                {
                    ViewData["msg"] = "请先获取密钥！".AlertOffPage();
                    return View(newModel);
                }
                if (pwdKey.ToString() == model.InputPwdKey)
                {
                    var count = new UserManage().EditTakePwd(LoginUserID, model.NewPwd);
                    if (count > 0)
                        ViewData["msg"] = "".Redirect("提款密码修改成功！");
                    else
                    { 
                        ViewData["msg"] = "操作失败！请稍后重新操作。".AlertOffPage();
                        TempData["pwdKey"] = pwdKey;
                    }
                }
                else
                {
                    ModelState.AddModelError("InputPwdKey", "密钥输入错误");
                    TempData["pwdKey"] = pwdKey;
                }
            }
            return View(newModel);
        }
        #endregion

        #region 冻结金额
        public JsonResult FreezMoney()
        {
            var count = -1;
            var msg = "";
            var email = new UserManage().Select<Person,string>(s => s.FirstOrDefault(p => p.UserID == LoginUserID).Email);
            if (string.IsNullOrEmpty(email))
                msg = "您还没有设置邮箱，请先设置邮箱。";
            else if (LoginUser.State == UserState.Freez)
                count = 1;
            else
            {
                try
                {
                    count = new UserManage().UserFreezeMoney(LoginUserID,UserState.Normal);
                }
                catch (AppException a) { msg = a.Message; }
                catch (Exception) { msg = "操作失败！"; }
                if (count > 0)
                {
                    LoginUser.State = UserState.Freez;
                    LoginUser.IsLoad = true;
                }
            }
            return Json(new {count,msg }, JsonRequestBehavior.AllowGet);
        }
        //用户自定义控件
        public ActionResult FreeMoney()
        {
            if (LoginUser.State == UserState.Normal)
                ViewData["msg"] = "您当前状态已是解冻，不需要再解冻！".AlertOffPage();
            else
            {
                var key = MD5.Create().ComputeHash(Guid.NewGuid().ToString());
                try
                {
                    var email = new UserManage().Select<Person,string>(s => s.Where(p => p.UserID == LoginUserID).Select(p=>p.Email).FirstOrDefault());
                    if (string.IsNullOrEmpty(email)) 
                    {

                        ViewData["msg"] = "您还没有设置安全邮箱，请先设置邮箱！".AlertOffPage();
                        return View();
                    }
                    var flag = new Jmail().Send(email, "解冻密钥", key);
                    ViewData["msg"] = "密钥已发送到您的安全邮箱，请查收！".AlertOffPage();
                    TempData["GetMoney_Key"] = key;
                }
                catch (AppException e)
                {
                    ViewData["msg"] = e.Message.AlertOffPage();
                }
                catch (Exception)
                {
                    ViewData["msg"] = "邮件发送失败,请稍后重新操作!".AlertOffPage();
                }
            }
            return View();
        }

        public JsonResult GetMoney(string key)
        {
            var count = -1;
            var msg = string.Empty;
            if (!string.IsNullOrEmpty(key))
            {
                var sessionKey = TempData["GetMoney_Key"] as string;
                if (string.IsNullOrEmpty(sessionKey))
                    msg = "请先获取密钥。";
                else if (sessionKey.Equals(key))
                {
                    try
                    {
                        count = new UserManage().UserFreeMoney(LoginUserID);
                        if (count > 0)
                        {
                            LoginUser.State = UserState.Normal;
                            msg = "已成功解冻！";
                            LoginUser.IsLoad = true;
                        }
                        else
                            msg = "操作失败！请重新操作。";
                    }
                    catch (AppException a) { msg = a.Message; }
                    catch (Exception) { msg = "操作失败！请重新操作。"; }
                }
                else
                {
                    msg = "密钥输入错误！请重新输入";
                    TempData["GetMoney_Key"] = sessionKey;
                }
            }
            else
                msg = "请输入密钥！";
            return Json(new { count,msg}, JsonRequestBehavior.AllowGet);
        }

        //冻结金额页面
        public ActionResult FreezUserMoney()
        {
            var flag = LoginUser.State == UserState.Freez;
            ViewData["IsFreez"] = flag;
            return View();
        }
        #endregion

        #region 帮助中心
        #region 玩法介绍
        public ActionResult IntroPlay()
        {
            return View();
        }
        #endregion

        #region 常见问题
        public ActionResult Questions()
        {
            return View();
        }
        #endregion
        #endregion

        #region 游戏工具
        public ActionResult PlayTool()
        {
            return View();
        }
        public ActionResult OtherTool()
        {
            return View();
        }
        #endregion

        #region 查看用户奖金
        public ActionResult WinMoney(LotteryTypeType? lottery, Guid? uid)
        {
            var models = new QianBuo.Lottery.Web.Models.User.WinMoneyModel();
            if (uid == null)
            {
                uid = LoginUserID;
                models.UserName = base.LoginUser.LoginName;
            }
            else
            {
                var user = new UserManage().Select(s => s.FirstOrDefault(p => p.ID == uid.Value && p.Commands.Contains(LoginUserID.ToString())));
                if (user == null)
                {
                    var msg = (Request["returnurl"] ?? Url.Action("Childs", "Surrogate")).Redirect("您要查看的用户不存在！");
                    return Content(msg);
                }
                models.UserName = user.LoginName;
            }
            models.Uid = uid.Value;
            models.UseSiteWinMoney = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            models.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);


            if (!lottery.HasValue && CacheManage.Lottery.Count > 0)
                lottery = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).First().Key;
            var PM = new PlayTypeOptionManage();
            var useroption = PM.GetWinMoneyOption(uid, (int)lottery.Value.GetDefaultLottery(), null,true).ToArray();
            models.Lotterys = CacheManage.LotteryTypes.OrderBy(p=>p.Value.Sort).Select(p => new SelectListItem { Text = p.Value.Name, Value = p.Key.ToString(), Selected = p.Key == lottery }).ToList();
            models.Ratios = CacheManage.Ratio.Select(p => new SelectListItem { Text = p.Value.Name + "模式", Value = ((double)p.Value.BackMoneyDifference * 100).ToString(), Selected = p.Key == 1 }).ToList();
            models.WinModels = CacheManage.WinModel.Values.OrderBy(p => p.ID).ToNameValue(p => p.Name, p => p.ID);

            if (lottery.HasValue)
            {
                models.WinMoneys = useroption.GroupBy(p => p.PlayTypeID)
                    .OrderBy(p => p.Key)
                    .ToNameValue(
                        p => new NameValueItem<int, string>
                            {
                                Key = p.Key,
                                Value = CacheManage.PlayType[p.Key].PlayTypeList.Name
                            },
                        p => p.Select(pp => new WinMoneyItem
                            {
                                BadkMoneyRatio = Math.Round(pp.BackMoneyRatio * 100, 9),
                                BackMoneyToWinMoneyRatio = pp.BackMoneyToWinMoneyRatio,
                                MaxBackMoneyToWinMoney = Math.Round(pp.MaxBackMoneyToWinMoney * 100, 9),
                                WinMoney = pp.WinMoney,
                                WinModelID = pp.WinMoneyModelID,
                                PlayTypeID = pp.PlayTypeID
                            }));
            }

            return View(models);
        }
        #endregion
    }
}
